package com.ctrip.ec.biz.dao.order;

import com.ctrip.ec.biz.dao.goods.GoodsSpecDao;
import com.ctrip.ec.biz.dao.payment.PaymentDao;
import com.ctrip.ec.biz.entity.goods.GoodsSpecEntity;
import com.ctrip.ec.biz.entity.order.OrderGoodsEntity;
import com.ctrip.ec.biz.entity.order.OrderStatus;
import com.ctrip.ec.biz.entity.order.StatusSumModel;
import com.ctrip.ec.dal.DaoBase;
import com.ctrip.ec.biz.entity.order.OrderEntity;
import com.ctrip.ec.dal.DbAccess;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.sql.Date;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.List;
import java.util.stream.Collectors;


@Service
public class OrderDao extends DaoBase<OrderEntity> {

    @Autowired
    private PaymentDao payment;

    @Autowired
    private GoodsSpecDao goodsSpec;

    @Autowired
    private  OrderGoodsDao orderGoods;

    public OrderDao() {
        super(OrderEntity.class);
    }

    public OrderDao(DbAccess db) {
        super(OrderEntity.class, db);
    }

    public void updateStatus(OrderStatus status, Long id) throws SQLException {
        String sql = "update " + this.getTableName() + " set order_status=? where id =?";
        this.db.execute(sql, status.getId(), id);

    }



    /**
     * 取消超时未付款的
     */
    public void cancelUnpay() throws SQLException {
        String sql = "select * from " + this.getTableName() + " where date_add(order_time, interval 30 minute) < now() and order_status=" + OrderStatus.待支付.getId();
        List<OrderEntity> list = this.db.query(OrderEntity.class,sql);
        cancel(list);
    }

    public  void cancel(List<OrderEntity> orderList) throws SQLException {
        if (orderList != null && orderList.size() > 0) {
            try {
                payment.getDb().begin();
                payment.cancel(orderList.stream().map(t -> t.getPaymentId()).distinct().collect(Collectors.toList()));
                for (OrderEntity orderEntity : orderList) {

                    List<OrderGoodsEntity> goodsList = orderGoods.listByOrderId(orderEntity.getId());
                    //取消订单需要还回库存
                    for (OrderGoodsEntity orderGoodsEntity : goodsList) {
                        GoodsSpecEntity goodsSpecEntity = goodsSpec.entityWithLock(orderGoodsEntity.getSpecId());
                        if (goodsSpecEntity != null) {
                            goodsSpecEntity.setStoreCount(goodsSpecEntity.getStoreCount() + orderGoodsEntity.getBuyNum());
                            goodsSpec.save(goodsSpecEntity);
                        }
                    }
                    //修改订单状态
                    orderEntity.setOrderStatus(OrderStatus.已取消.getId());
                    this.save(orderEntity);
                }
                payment.getDb().commit();
            } catch (Exception ex) {
                payment.getDb().rollback();
                throw ex;
            }

        }
    }

    public BigDecimal todaySales(Long memberId) throws SQLException {
        Date date = new Date(System.currentTimeMillis());
        String sql = "select ifnull(sum(goods_amount-back_amount),0) as goods_amount  from " + this.getTableName() + " where member_id=? and order_status >=? and order_time>=?";
        BigDecimal amount = this.db.getScalar(BigDecimal.class,sql,memberId,OrderStatus.已发货.getId(),date);
        return amount;
    }

    public BigDecimal todaySalesAgency(Long memberId) throws SQLException {
        Date date = new Date(System.currentTimeMillis());
        String sql = "select ifnull(sum(agency_amount),0) as goods_amount  from " + this.getTableName() + " where member_id=? and order_status >=? and order_time>='" + date.toString() + "'";
        BigDecimal amount = this.db.getScalar(BigDecimal.class,sql,memberId,OrderStatus.已发货.getId());
        return amount;
    }

    public  BigDecimal currentMonthSales(Long memberId) throws  SQLException{
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH);
       // int day = cal.get(Calendar.DATE);
        String from = year + "-" + month + "-1";

        String sql = "select ifnull(sum(goods_amount-back_amount),0) as goods_amount  from " + this.getTableName() + " where member_id = ? and order_status >=? and order_time>='" + from + "'";
        BigDecimal amount = this.db.getScalar(BigDecimal.class,sql,memberId,OrderStatus.已发货.getId());
        return amount;
    }

    public  BigDecimal currentMonthAgency(Long memberId) throws  SQLException{
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH);
        // int day = cal.get(Calendar.DATE);
        String from = year + "-" + month + "-1";

        String sql = "select ifnull(sum(agency_amount),0) as goods_amount  from " + this.getTableName() + " where member_id = ? and order_status >=? and order_time>='" + from + "'";
        BigDecimal amount = this.db.getScalar(BigDecimal.class,sql,memberId,OrderStatus.已发货.getId());
        return amount;
    }

    public  BigDecimal lastMonthSalse(Long memberId) throws  SQLException{
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH);
        // int day = cal.get(Calendar.DATE);
        String to = year + "-" + month + "-1";

        cal.add(Calendar.MONTH,-1);
        year = cal.get(Calendar.YEAR);
        month = cal.get(Calendar.MONTH);

        String from = year + "-" + month + "-1";

        String sql = "select ifnull(sum(goods_amount-back_amount),0) as goods_amount  from " + this.getTableName() + " where member_id = ? and order_status >=? and order_time>='" + from + "' and order_time<='" + to + "'";
        BigDecimal amount = this.db.getScalar(BigDecimal.class,sql,memberId,OrderStatus.已发货.getId());
        return amount;

    }

    public  BigDecimal lastMonthAgency(Long memberId) throws  SQLException{
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH);
        // int day = cal.get(Calendar.DATE);
        String to = year + "-" + month + "-1";

        cal.add(Calendar.MONTH,-1);
        year = cal.get(Calendar.YEAR);
        month = cal.get(Calendar.MONTH);

        String from = year + "-" + month + "-1";

        String sql = "select ifnull(sum(agency_amount),0) as goods_amount  from " + this.getTableName() + " where member_id = ? and order_status >=? and order_time>='" + from + "' and order_time<='" + to + "'";
        BigDecimal amount = this.db.getScalar(BigDecimal.class,sql,memberId,OrderStatus.已发货.getId());
        return amount;

    }


    public List<StatusSumModel> statusSum(Long memberId) throws SQLException {
        String sql = "select count(*) as count,order_status from " + this.getTableName() + " where member_id=? group by order_status";
        List<StatusSumModel> list =  this.db.query(StatusSumModel.class,sql,memberId);
        return list;
    }


}
